//
//  FPluginFake.m
//  Foundation
//
//  Created by 三井 on 2019/10/18.
//

#import "FPluginFake.h"
#import "FPluginWrappedData.h"
#import "FPluginHost.h"
#import "FPlugin.h"

@interface FPluginFake ()

@property (nonatomic, strong) FPluginHost *pluginHost;

@end

@implementation FPluginFake

+ (instancetype)fakeFor:(id)source {
    FPluginFake *fake = [self alloc];
    fake.source = source;
    return fake;
}

- (BOOL)canHandle:(FPluginWrappedData *)data {
    if (![data isKindOfClass:FPluginWrappedData.class]) {
        return NO;
    }
    return [[self.plugin.class identifier] isEqualToString:data.from];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [self.source methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation invokeWithTarget:self.source];
}

- (BOOL)isFake {
    return YES;
}

#pragma mark - Cascade Plugin
- (FPluginHost *)pluginHost {
    if (!_pluginHost) {
        _pluginHost = [self hostFor:nil];
    }
    return _pluginHost;
}

- (NSArray<NSString *> *)pluginPriority {
    return self.pluginHost.pluginPriority;
}

- (NSInteger)plghost_load:(FPluginArg *)arg {
    FPluginHost *host = [self pluginHost:arg];
    
    if (self.pluginPriority) {
        host.pluginPriority = self.pluginPriority;
    }
    
    return [host loadPlugins:arg];
}

- (void)plghost_refresh:(FPluginArg *)arg {
    FPluginHost *host = [self pluginHost:arg];
    [host refreshPlugins:arg];
}

- (void)plghost_unload {
    
}

- (FPluginHost *)hostFor:(FPluginArg *)arg {
    return [[FPluginHost alloc] initWithHost:arg.hostIdentifier];
}

- (FPluginHost *)pluginHost:(FPluginArg *)arg {
    FPluginHost *host = self.pluginHost;
    if (![host.hostIdentifier isEqualToString:arg.hostIdentifier]) {
        [host reloadWithHost:arg.hostIdentifier];
    }
    
    return host;
}

@end

@implementation NSObject (FPluginFake)

- (BOOL)isFake {
    return NO;
}

@end
